package message

import (
	"cat_mouse/infra/common"
	"cat_mouse/infra/utils/config"
	"cat_mouse/infra/utils/log"
	"cat_mouse/infra/utils/uuid"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"strconv"
	"sync"
)

var (
	aLiYunMsgClient     *ALiYunMsgClient
	aLiYunMsgClientOnce sync.Once
)

type ALiYunMsgClient struct {
	smsDto *config.ALiYun
}

func (s *ALiYunMsgClient) SendMessage(phoneNumber, code string) {
	var (
		client   *dysmsapi.Client
		request  *dysmsapi.SendSmsRequest
		response *dysmsapi.SendSmsResponse
		err      error
	)
	if client, err = dysmsapi.NewClientWithAccessKey(s.smsDto.RegionId, s.smsDto.AccessKeyId, s.smsDto.AccessKeySecret); err != nil {
		log.Logger.Errorf("dysmsapi.NewClientWithAccessKey error: %s", err)
		return
	}
	// 阿里云短信请求参数
	request = dysmsapi.CreateSendSmsRequest()
	request.Scheme = s.smsDto.Scheme
	request.PhoneNumbers = phoneNumber
	request.SignName = s.smsDto.SignName
	request.TemplateCode = s.smsDto.TemplateCode
	request.TemplateParam = code
	request.OutId = strconv.FormatInt(uuid.SnowFlakeId(), 10)

	if response, err = client.SendSms(request); err != nil {
		log.Logger.Errorf("client SendSms error: %s", err)
		return
	}
	// 短信网关网络错误
	if len(response.GetHttpContentString()) == 0 {
		log.Logger.Error(common.SmsNetworkError)
		return
	}
	if !(response.IsSuccess() && response.Code == "OK") {
		log.Logger.Errorf("ALiYunMsgClient SendSms failed: %s", response.GetHttpContentString())
	}
}

func NewALiYunMsgClient() *ALiYunMsgClient {
	aLiYunMsgClientOnce.Do(func() {
		aLiYunMsgClient = &ALiYunMsgClient{smsDto: &config.ALiYun{}}
	})
	return aLiYunMsgClient
}
